package com.springboot.seckill.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;


/**
 * @Author: HuangDekai
 * @Date: 2022/3/16 13:01
 * @Version: 1.0
 * @since: jdk11
 */
@Component
public class ValidatorImpl implements InitializingBean {
    private Validator validator;

    /**
     * 实现校验方法并返回校验结果
     * @param bean bean
     * @return 校验结果
     */
    public ValidationResult validate(Object bean) {
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<Object>> constraintViolationSet = validator.validate(bean);
        if (!constraintViolationSet.isEmpty()) {
            //有错误
            result.setHasErrors(true);
            constraintViolationSet.forEach(
                    constraintViolation -> {
                        String errMsg = constraintViolation.getMessage();
                        String propertyName = constraintViolation.getPropertyPath().toString();
                        result.getErrorMsgMap().put(propertyName, errMsg);
                    }
            );
        }
        return result;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //将javax.validation validator用工厂化的初始化方式使其实例化
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();

    }
}
